package com.example.satoken.config.saInterceptor;

import cn.dev33.satoken.stp.StpUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 自定义拦截器（token续期 和 token定期刷新）
 */
public class CustomInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // 获取过期时间配置
        long tokenTimeout = StpUtil.getTokenTimeout();

        /**
         * token没过期，过期时间不是-1(永久)的时候，每次请求都刷新过期时间,在90s不操作就过期了。
         */

        if (tokenTimeout != -1) {
            // 用于token续期
            StpUtil.renewTimeout(900000);
            StpUtil.updateLastActivityToNow();
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}
